package com.example.cwproject.controller;


import cn.hutool.core.io.FileUtil;
import com.example.cwproject.common.AuthAccess;
import com.example.cwproject.common.Result;
import com.example.cwproject.entity.User;
import com.example.cwproject.service.UserService;
import com.example.cwproject.mapper.UserMapper;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/user")
public class UserController {

    @Value("${ip}")  //默认值
    String ip;

    @Value("${server.port}")
    String port;

    @Autowired
    private UserService userService;

    //修改用户信息
    @PostMapping("/update")
    public Result update(@RequestBody User user){

        userService.updateUser(user);
        return Result.success();
    }

    //根据email返回用户所有信息
    @GetMapping("/findUserByEmail")
    public User findByEmail(String email){
        return userService.findByEmail(email);
    }

    //修改密码
    @PostMapping("/modifyPassword")
    public Result modifyPassword(@RequestBody User user){
        userService.modifyPassword(user.getPassword(), user.getEmail());
        return Result.success();
    }

    //上传头像
    @RequestMapping("/uploadAvatar")
    @ResponseBody
    public String uploadAvatar(@RequestParam("file") MultipartFile file, String email) throws IOException {

        String originalFilename = file.getOriginalFilename();   //获得文件的原始名称
        String mainName = FileUtil.mainName(originalFilename);  // 获得文件的主名称
        String extName = FileUtil.extName(originalFilename);  //获得文件后缀名
        String projectPath = System.getProperty("user.dir");    // D:\project\CwProject
        String filesPath = projectPath + "/avatarImage"; //文件的存储目录 D:\project\CwProject\files
        String fileRealPath = filesPath + File.separator + originalFilename; //  D:\project\CwProject\files\文件名称

        File saveFile = new File(fileRealPath);
        if(!saveFile.getParentFile().exists()){
            saveFile.getParentFile().mkdirs();  //如果当前文件的父目录不存在，就创建
        }
        if(saveFile.exists()){  //若当前上传的文件已存在，就需要重命名文件名称
            originalFilename =  System.currentTimeMillis()+ "_" + mainName + "." + extName;
            saveFile = new File(filesPath + File.separator + originalFilename);
        }
        file.transferTo(saveFile);//存储文件到本地磁盘中
        String url = "http://"+ip+":"+port+ "/user/download/" + originalFilename;
        userService.uploadAvatar(url, email);
        return url;//返回文件的链接，该链接就是文件的下载地址（后台提供）
    }

    @AuthAccess
    @GetMapping("/download/{filename}")
    public void download(@PathVariable String filename, HttpServletResponse response) throws IOException {

        String projectPath = System.getProperty("user.dir");
        String filesPath = projectPath + "/avatarImage" + File.separator + filename; //本地目录
        if(!FileUtil.exist(filesPath)){     //通过FileUtil方法， 判断如果当前上传的文件已存在，就重命名文件名称
            return;
        }
        byte[] bytes = FileUtil.readBytes(filesPath);  //文件的字节流数组
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();;
        outputStream.close();
    }


}



